package com.sky.aspect;

import com.sky.annotation.AutoFill;
import com.sky.context.BaseContext;
import com.sky.enumeration.OperationType;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.time.LocalDateTime;

//自定义切面类
@Aspect
@Component
@Slf4j
public class AutoFillAspect {
    //切入点加上注解限制方法
    @Pointcut("execution(* com.sky.mapper.*.*(..)) && @annotation(com.sky.annotation.AutoFill)")
    public void autoFillPointCut(){}
    //前置通知,在对应的方法执行前执行公共字段的复制
    @Before("autoFillPointCut()")
    public void autoFill(JoinPoint joinPoint) {
        log.info("开始进行数据填充");
        //获取拦截方法的数据类型
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        AutoFill autoFill = methodSignature.getMethod().getAnnotation(AutoFill.class);
        OperationType value = autoFill.value();
        //获取拦截的方法参数
        Object[] args = joinPoint.getArgs();
        if (args == null || args.length == 0){
            return;
        }
        Object entity = args[0];
        //准备赋值的数据
        LocalDateTime now = LocalDateTime.now();
        Long id= BaseContext.getCurrentId();
        if (value == OperationType.INSERT){
            //4个公共字段
            try {
                Method  setCreateTime = entity.getClass().getMethod("setCreateTime", LocalDateTime.class);//获取 方法
                Method  setCreateUser = entity.getClass().getMethod("setCreateUser", Long.class);
                Method  setUpdateTime = entity.getClass().getMethod("setUpdateTime", LocalDateTime.class);
                Method  setUpdateUser = entity.getClass().getMethod("setUpdateUser", Long.class);
                setCreateTime.invoke(entity,now);
                setUpdateTime.invoke(entity,now);
                setCreateUser.invoke(entity,id);
                setUpdateUser.invoke(entity,id);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }

        }else if (value == OperationType.UPDATE){
                try {
                    Method  setUpdateTime = entity.getClass().getMethod("setUpdateTime", LocalDateTime.class);
                    Method  setUpdateUser = entity.getClass().getMethod("setUpdateUser", Long.class);
                    setUpdateTime.invoke(entity,now);
                    setUpdateUser.invoke(entity,id);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
        }
    }
}
